package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.RequestParams;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.OrderDetailService;
import com.hmall.order.service.OrderLogisticsService;
import com.hmall.order.utils.IdWorker;
import com.hmall.order.utils.UserHolder;
import com.hmall.user.service.IAddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderLogisticsService orderLogisticsService;


    @Transactional
    @Override
    public Long createOrder(RequestParams params) {

//        IdWorker worker = new IdWorker(1,1,1);

        // 根据itemId查询商品信息
        Item item = itemClient.getById(params.getItemId());
        // 基于商品价格、购买数量计算商品总价：totalFee
        Long totalFee = item.getPrice() * params.getNum();
        // 封装Order对象，初识status为未支付
        Order order = new Order();
        order.setTotalFee(totalFee);
        order.setPaymentType(params.getPaymentType());
        order.setUserId(UserHolder.getUser());
        order.setStatus(1);

        // 将order写入数据库tb_order表中
        this.save(order);

        // 将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(order.getId()); // 订单编号
        orderDetail.setItemId(item.getId()); // 商品id
        orderDetail.setNum(params.getNum()); // 商品数量
        orderDetail.setPrice(item.getPrice()); // 商品单价
        orderDetail.setName(item.getName()); // 商品标题
        orderDetail.setImage(item.getImage()); // 图片
        orderDetail.setSpec(item.getSpec()); // 商品规格数据
        orderDetailService.save(orderDetail);

        // 根据addressId查询user-service服务，获取地址信息
        Long addressId = params.getAddressId();
        Address address = userClient.findAddressById(addressId);

        // 将地址封装为OrderLogistics对象，写入tb_order_logistics表
        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address, orderLogistics);
        orderLogistics.setOrderId(order.getId());

        orderLogisticsService.save(orderLogistics);

        // 调用item-service的减库存接口
        try {
            itemClient.updateStock(params.getItemId(), params.getNum());
        } catch (Exception e) {
            throw new RuntimeException("库存不足！");
        }
        return order.getId();
    }

    @Override
    public void closeTimeoutOrder() {
        // 查询status为1，并且下单时间超过30分钟的
//        List<OrderDetail> orderDetailList = orderDetailService.getBaseMapper().queryTimeoutOrderDetail();
        List<OrderDetail> orderDetailList = orderDetailMapper.queryTimeoutOrderDetail();
        if(orderDetailList==null||orderDetailList.size()==0){
            return;
        }

        // 恢复库存
        for (OrderDetail orderDetail : orderDetailList) {
            itemClient.updateStock(orderDetail.getItemId(), -orderDetail.getNum());
        }

        // 收集订单id
        List<Long> orderIdList = orderDetailList.stream().map(OrderDetail::getOrderId).collect(Collectors.toList());

        // 把满足以上条件的订单状态修改成 5（订单取消）
        LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Order::getStatus, 5);
        updateWrapper.set(Order::getCloseTime, new Date());
        updateWrapper.in(Order::getId, orderIdList);
        this.update(updateWrapper);
        System.out.println(" 执行定时任务....");
    }
}
